'use strict';
import React from 'react';
import {connect} from 'dva/index';
import {Button, Card, Col, Drawer, Dropdown, Form, Menu, Popconfirm, Row, Select, Statistic, Table} from 'antd';
import styles from '../index.less';

import ViewTitle from '../../components/ViewTitle';
import FormBase from '../../components/Base/FormBase';
import {FormField, ModalView, SearchForm} from 'antd-extra';
import moment from 'moment';
import 'moment/locale/zh-cn';

import ModalCreateOrEditRentOrder from "./modal/ModalCreateOrEditRentOrder";
import _ from "lodash";
import ModalPaid from "./modal/ModalPaid";
import Icon from "antd/es/icon";
import notify from "../../components/NotificationExtra";
import ModalSalesOrderDetail from "./modal/ModalSalesOrderDetail";
import ModalStatistics from "./modal/ModalStatistics";

moment.locale('zh-cn');
const table = 'SalesOrder';
const title = '租用订单';

@Form.create()
@connect(({
            user,
            global,
            sales,
            store,
            dict,
            customer
          }) => ({...user, ...global, ...sales, ...store, ...dict, ...customer}))
export default class Review extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    this.props.dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'sales/findMany',
      payload: {projectType: '租用'}
    });
  }

  onDelete = record => {
    const {code} = record;
    this.props.dispatch({
      type: 'sales/deleteOne',
      payload: {code}
    })
      .then(res => {
        this.requestReturn(res);
        this.componentDidMount();
      });
  };
  onCreate = async () => {
    const {model = {}, dispatch, customers = [], materials = []} = this.props;
    const code = this.getCode('SAL');
    const values = {code};
    ModalView.open(ModalCreateOrEditRentOrder, {
      title: '新建租用订单',
      width: '1580px',
      maskClosable: false
    }, {
      values,
      model,
      customers,
      materials,
      dispatch,
      table,
      cols: 4,
      callback: (data) => {
        data.table = table;
        data.reviewStatus = '待审核';
        this.props.dispatch({
          type: 'sales/create',
          payload: data
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }
    });
  };
  onCopy = async (values) => {
    const _values = _.cloneDeep(values);
    _values.code = this.getCode('SAL');
    delete _values["_id"];
    const {dispatch, customers = [], materials = []} = this.props;
    const model = this.props[`${table}Model`];
    let _title = `复制${title}`;
    _.map(model, (item, key) => {
      item.defaultValue = _values[key];
    });

    ModalView.open(ModalCreateOrEditRentOrder, {
      title: _title,
      width: '1580px',
      maskClosable: false
    }, {
      model, customers, materials,
      values: _values,
      dispatch: dispatch,
      table,
      title: _title,
      cols: 4,
      callback: (data) => {
        data.table = table;
        data.reviewStatus = '待审核';
        delete data['createdTs'];
        this.props.dispatch({
          type: 'sales/create',
          payload: data
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }
    });
  };
  onEdit = async (values) => {
    const {dispatch, customers = [], materials = []} = this.props;
    const model = this.props[`${table}Model`];
    let _title = `编辑${title}`;
    _.map(model, (item, key) => {
      item.defaultValue = values[key];
    });
    ModalView.open(ModalCreateOrEditRentOrder, {
      title: _title,
      width: '1580px',
      maskClosable: false
    }, {
      model, customers, materials,
      values,
      dispatch: dispatch,
      table, cols: 4,
      title: _title,
      disabledProps: ['code'],
      callback: (data) => {
        console.log('dataaa', data);
        data.createUser = this.getLoginUser();
        data.createUsername = this.getLoginUsername();
        data.tenantCode = this.getTenantCode();
        data.table = table;
        console.log('dataaa', data);
        this.props.dispatch({
          type: 'sales/updateOne',
          payload: data
        }).then(res => {
          this.requestReturn(res);
          this.componentDidMount();
        });
      }
    });
  };


  menu = record => {
    return (
      <Menu>

        <Menu.Item disabled={record.reviewStatus === '同意'}>
          <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}
             onClick={() => this.onEdit(record)}>编辑</a>
        </Menu.Item>

        <Menu.Item>
          <a style={{marginRight: '6px'}}
             onClick={() => this.onCopy(record)}>复制</a>
        </Menu.Item>
      </Menu>);
  };

  getTableCols = () => {
    const model = this.props[`${table}Model`];
    const temp = this.getTableColumns(model);
    temp.push(
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 160, fixed: 'right',
        render: (value, record) => {
          return (
            <span>
           {<a style={{marginRight: '6px'}}
               onClick={() => this.setState({showDetail: true, record})}>详情</a>}

              {/*{*/}
              {/*  <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}*/}
              {/*     onClick={() => this.onEdit(record)}>编辑</a>*/}
              {/*}*/}
              {<Popconfirm
                title="确认删除"
                onConfirm={() => this.onDelete(record)}
                okText="是"
                cancelText="否"

              >
                <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}>删除</a>
              </Popconfirm>}
              <Dropdown overlay={this.menu(record)}>
              <a className="ant-dropdown-link">
                更多 <Icon type="down"/>
              </a>
            </Dropdown>
            </span>
          );
        }
      });
    return temp;

  };

  getSearchFields = () => {
    const model = this.props[`${table}Model`];
    if (!model) return [];
    const arr = [];
    this.getSearchField(arr, model, "");
    const {prods} = model;
    this.getSearchField(arr, prods, "prods.");
    console.log('get searchFields', arr);
    _.remove(arr,item=>item.key==="projectType")
    return arr;
  };

  render() {
    const {sales = {}, _notify, form} = this.props;
    const {record = {}, showDetail, showStatistics} = this.state;

    if (_notify && this.state._notify !== _notify) {
      notify(_notify);
      this.state._notify = _notify;
    }

    const {amount, count, array} = sales;
    return (
      <Form className={styles.content}>
        <ViewTitle
          title={`${title}列表`}
          level={1}
          actions={[
            <Button type="primary" onClick={() => this.onCreate(undefined)}>添加</Button>
          ]}></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={4}
          min={8}
          expandText="展开"
          form={form}
        >
          {this.getSearchFields()}
        </SearchForm>
        <div style={{background: '#ECECEC', padding: '30px'}}>
          <Row gutter={16}>
            <Col span={10}>
              <Card>
                <Statistic
                  title="租用商品总数量"
                  value={count}
                  precision={2}
                  valueStyle={{color: '#3f8600'}}
                  suffix="KG"
                />
              </Card>
            </Col>
            <Col span={10}>
              <Card>
                <Statistic
                  title="租用商品总金额"
                  value={amount}
                  precision={2}
                  valueStyle={{color: '#cf1322'}}
                  suffix="元"
                />
              </Card>
            </Col>
            <Col span={4}>
              <Card
                onClick={() => {
                  this.setState({showStatistics: true});
                }}
              >
                <Statistic
                  title="更多"
                  value={'点击查看'}
                  precision={3}
                  valueStyle={{color: '#35f'}}
                />

              </Card>
            </Col>
          </Row>
        </div>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.getTableCols()}
          dataSource={array}
          scroll={{x: true}}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
          //  scroll={{ x: 1300 }}
        ></Table>

        {showDetail && <Drawer
          visible={showDetail}
          title={`${title}详情`}
          placement="left"
          width={'80%'}
          style={{padding: 0}}
          // maskClosable={false}
          onClose={() => {
            this.setState({showDetail: false});
            this.componentDidMount();
          }}
        >
          <ModalSalesOrderDetail
            values={record}
          > </ModalSalesOrderDetail>
        </Drawer>}

        {showStatistics && <Drawer
          visible={showStatistics}
          title={`统计`}
          placement="left"
          width={'80%'}
          style={{padding: 0}}
          // maskClosable={false}
          onClose={() => {
            this.setState({showStatistics: false});
            this.componentDidMount();
          }}
        >
          <ModalStatistics
            values={array}
          > </ModalStatistics>
        </Drawer>}
      </Form>
    );
  }

}
